<?php
/**
 * 城市地址管理
 * Created by Sublime Text 3.
 * @authors Rejeo (rejeo@qq.com)
 * @date    2018-04-22 23:20:45
 * @version $Id$
 */
namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\common\model\City as CityModel;

class City extends Controller
{
    private $link;

    // 重载父类的初始化设置
    public function _initialize()
    {
        $this->link = new CityModel();
    }

    // 显示地址列表
    public function index(Request $request)
    {
        $parentId = $request->get('parent_id', 0, 'intval');
        $res = $this->link->getNormalCitysByParentId($parentId);
        // 添加必要的url参数，适用于非iframe 框架的单页面
        // $page = $res->appends($request->param())->render();
        // 通用的方式
        // $page = $res->appends(['test'=>'asd'])->render();
        $page = $res->render();

        $this->assign('res',$res);
        $this->assign('page',$page);
        return $this->fetch();
    }

    // 添加地址
    public function add()
    {
        $res = $this->link->getNormalFirstCity();
        // $res =[];
        $this->assign('res',$res);
        return $this->fetch();
    }

    // 编辑页面
    public function edit($id=0)
    {
        if (intval($id)<0) {
            return $this->error('参数不合法！');
        }
        $city = $this->link->get($id);// 需要数据表主键为id
        $citys = $this->link->getNormalFirstCity();
        return $this->fetch('',[
            'city'=>$city,
            'citys'=>$citys,
        ]);
    }

    // 保存地址
    public function save(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post(); // 获取所有的post参数
            $validate = $this->validate($data,'City.add'); // 实例化验证规则
            if(TRUE !== $validate){
                return $this->error($validate);
            }
            $data['uname'] = hanziTopinyin($data['name']); // 汉子转换为拼音
            if (!empty($data['id'])) {
                return $this->update($data);
            }
            $flag = $this->link->add($data);
            if ($flag) {
                return $this->success('地址添加成功！');
            }else{
                return $this->error('Data Error！');
            }
        }else{
            return $this->error('提交有误');
        }
    }

    // 状态修改
    public function status(Request $request)
    {
        $data = $request->get();
        $validate = $this->validate($data,'City.status');// 实例化验证规则
        if(TRUE !== $validate){
            return $this->error($validate);
        }
        $res = $this->link->save(['status'=>$data['status']],['id'=>$data['id']]);
        if ($res) {
            return $this->success('状态设置成功！');
        }
        return $this->success('状态设置失败！');
    }

    // 更新地址
    public function update($data)
    {
        $res = $this->link->save($data,['id'=>intval($data['id'])]);
        if ($res) {
            return $this->success('更新成功！');
        } else {
            return $this->error('更新失败！');
        }

    }

}
